package itsm.isperp.framework.web.utils;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

/**
 * 控制器工具
 * 
 * @author lizx
 * @date 2013-4-24
 */
public final class ControllerUtils {

	public static final Logger logger = LoggerFactory
			.getLogger(ControllerUtils.class);

	/**
	 * 获取一个表单
	 * 
	 * @return
	 */
	public static ModelAndView getView() {
		HttpServletRequest req = ContextHolder.getRequest();
		String requestURI = req.getRequestURI();
		logger.debug((new StringBuilder()).append("requestURI:")
				.append(requestURI).toString());
		String contextPath = req.getContextPath();

		int cxtIndex = requestURI.indexOf(contextPath);
		if (cxtIndex != -1)
			requestURI = requestURI.substring(cxtIndex + contextPath.length());
		String paths[] = requestURI.split("[/]");
		if (paths != null && paths.length == 5) {
			String jspPath = (new StringBuilder()).append("/").append(paths[1])
					.append("/").append(paths[2]).append("/").append(paths[3])
					.append(StringUtils.camelCaseWord(paths[4])).append(".jsp")
					.toString();
			return new ModelAndView(jspPath);
		}
		if (paths != null && paths.length == 4) {
			String jspPath = (new StringBuilder()).append("/").append(paths[1])
					.append("/").append(paths[2])
					.append(StringUtils.camelCaseWord(paths[3])).append(".jsp")
					.toString();
			return new ModelAndView(jspPath);
		} else {
			logger.error("your request url is not the right pattern, it is not allowed use this getAutoView method");
			throw new RuntimeException((new StringBuilder()).append("url:[")
					.append(requestURI)
					.append("] is not in this pattern:[/模块/实体/操作方法]")
					.toString());
		}
	}

}
